<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="温馨提示：本文也是以提问式阅读与探究源码的技巧展示。  1、回顾从前面的文章我们已经知道，Mybatis在执行SQL语句的扩展点为Executor、StatementHandler、ParameterHandler与ResultSetHandler，我们本节将以Executor为入口，向大家展示Mybatis插件的扩展机制。 我们先来看回顾一下Mybatis Executor的创建入口。 1.1">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Mybatis插件(Plugin)机制与实战">
<meta property="og:url" content="https://www.codingw.net/posts/3e30e205.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="温馨提示：本文也是以提问式阅读与探究源码的技巧展示。  1、回顾从前面的文章我们已经知道，Mybatis在执行SQL语句的扩展点为Executor、StatementHandler、ParameterHandler与ResultSetHandler，我们本节将以Executor为入口，向大家展示Mybatis插件的扩展机制。 我们先来看回顾一下Mybatis Executor的创建入口。 1.1">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190530205753805.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2019053021040719.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190530210628459.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2019053021182314.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-12T15:07:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:11:14.686Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20190530205753805.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/3e30e205.html"/>





  <title>源码分析Mybatis插件(Plugin)机制与实战 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/3e30e205.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Mybatis插件(Plugin)机制与实战</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-12T23:07:35+08:00">
                2020-10-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/mybatis/" itemprop="url" rel="index">
                    <span itemprop="name">mybatis</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/3e30e205.html" class="leancloud_visitors" data-flag-title="源码分析Mybatis插件(Plugin)机制与实战">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><blockquote>
<p>温馨提示：本文也是以提问式阅读与探究源码的技巧展示。</p>
</blockquote>
<h2 id="1、回顾"><a href="#1、回顾" class="headerlink" title="1、回顾"></a>1、回顾</h2><p>从前面的文章我们已经知道，Mybatis在执行SQL语句的扩展点为Executor、StatementHandler、ParameterHandler与ResultSetHandler，我们本节将以Executor为入口，向大家展示Mybatis插件的扩展机制。</p>
<p>我们先来看回顾一下Mybatis Executor的创建入口。</p>
<h3 id="1-1-Configuration-newExecutor"><a href="#1-1-Configuration-newExecutor" class="headerlink" title="1.1 Configuration#newExecutor"></a>1.1 Configuration#newExecutor</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Executor <span class="title">newExecutor</span><span class="params">(Transaction transaction, ExecutorType executorType)</span> </span>&#123;</span><br><span class="line">  executorType = executorType == <span class="keyword">null</span> ? defaultExecutorType : executorType;</span><br><span class="line">  executorType = executorType == <span class="keyword">null</span> ? ExecutorType.SIMPLE : executorType;</span><br><span class="line">  Executor executor;</span><br><span class="line">  <span class="keyword">if</span> (ExecutorType.BATCH == executorType) &#123;</span><br><span class="line">    executor = <span class="keyword">new</span> BatchExecutor(<span class="keyword">this</span>, transaction);</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ExecutorType.REUSE == executorType) &#123;</span><br><span class="line">    executor = <span class="keyword">new</span> ReuseExecutor(<span class="keyword">this</span>, transaction);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    executor = <span class="keyword">new</span> SimpleExecutor(<span class="keyword">this</span>, transaction);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (cacheEnabled) &#123;</span><br><span class="line">    executor = <span class="keyword">new</span> CachingExecutor(executor);</span><br><span class="line">  &#125;</span><br><span class="line">  executor = (Executor) interceptorChain.pluginAll(executor);   <span class="comment">// @1</span></span><br><span class="line">  <span class="keyword">return</span> executor;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1,：使用InterceptorChain.pluginAll(executor)进行拆件化处理。</p>
<p>思考：使用该方法调用后，会返回一个什么对象呢？如何自定义拆件，自定义插件如何执行呢？</p>
<p>那接下来我们带着上述疑问，从InterceptorChain类开始进行深入学习。</p>
<h2 id="2、InterceptorChain"><a href="#2、InterceptorChain" class="headerlink" title="2、InterceptorChain"></a>2、InterceptorChain</h2><p>从名字上看其大意为拦截器链。</p>
<h3 id="2-1-类图"><a href="#2-1-类图" class="headerlink" title="2.1 类图"></a>2.1 类图</h3><p><img src="https://img-blog.csdnimg.cn/20190530205753805.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<ul>
<li>InterceptorChain<br>拦截器链，其内部维护一个interceptors,表示拦截器链中所有的拦截器，并提供增加或获取拦截器链的方法，下面会重点分析pluginAll方法。</li>
<li>Interceptor<br>拦截器接口，用户自定义的拦截器需要实现该接口。</li>
<li>Invocation<br>拦截器执行时的上下文环境，其实就是目标方法的调用信息，包含目标对象、调用的方法信息、参数信息。其中包含一个非常重要的方法：proceed。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">proceed</span><span class="params">()</span> <span class="keyword">throws</span> InvocationTargetException, IllegalAccessException </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> method.invoke(target, args);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
该方法的主要目的就是进行处理链的传播，执行完拦截器的方法后，最终需要调用目标方法的invoke方法。</li>
</ul>
<p>记下来中先重点分析一下InterceptorChain方法的pluginAll方法，因为从开头也知道,Mybatis在创建对象时，是调用该方法，完成目标对象的包装。</p>
<span id="more"></span>

<h3 id="2-2-核心方法一览"><a href="#2-2-核心方法一览" class="headerlink" title="2.2 核心方法一览"></a>2.2 核心方法一览</h3><h4 id="2-2-1-pluginAll"><a href="#2-2-1-pluginAll" class="headerlink" title="2.2.1 pluginAll"></a>2.2.1 pluginAll</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">pluginAll</span><span class="params">(Object target)</span> </span>&#123;   <span class="comment">// @1</span></span><br><span class="line">  <span class="keyword">for</span> (Interceptor interceptor : interceptors) &#123;   <span class="comment">// @2</span></span><br><span class="line">    target = interceptor.plugin(target);         </span><br><span class="line">  <span class="comment">// @3</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> target;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：目标对象，需要被代理的对象。</p>
<p>代码@2：遍历InterceptorChain的拦截器链，分别调用Intercpetor对象的Plugin进行拦截(@3)。</p>
<p>那接下来有三个疑问？<br>问题1：InterceptorChain中的interceptors是从什么时候初始化的呢，即拦截链中的拦截器从何而来。<br>问题2：从前面也得知，无论是创建Executor，还是创建StatementHandler等，都是调用InterceptorChain#pluginAll方法，那是不是拦截器中的拦截器都会作用与目标对象，这应该是有问题的，该如何处理？<br>问题3：代理对象是如何创建的。</p>
<h4 id="2-2-1-addInterceptor"><a href="#2-2-1-addInterceptor" class="headerlink" title="2.2.1 addInterceptor"></a>2.2.1 addInterceptor</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addInterceptor</span><span class="params">(Interceptor interceptor)</span> </span>&#123;</span><br><span class="line">  interceptors.add(interceptor);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>要想知道interceptors是如何初始化的，我们只需要查看该方法的调用链即可。</p>
<p>一路跟踪到源头，我们会发现在初始化SqlSessionFactory时，会解析一个标签plugin，就可以得知，会在SqlSessionFacotry的一个属性中配置所有的拦截器。<br>具体配置示例如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;sqlSessionFactory&quot;</span> <span class="attr">class</span>=<span class="string">&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;dataSource&quot;</span> <span class="attr">ref</span>=<span class="string">&quot;shardingDataSource&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;mapperLocations&quot;</span> <span class="attr">value</span>=<span class="string">&quot;classpath*:META-INF/mybatis/mappers/OrderMapper.xml&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;plugins&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">array</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span> = <span class="string">&quot;teneantInteceptor&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.demo.inteceptor.TenaInteceptor&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">array</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>问题1已经解决。但后面两个问题似乎没有什么突破口。由于目前所涉及的三个类，显然不足以给我们提供答案，我们先将目光移到InterceptorChain所在包中的其他类，看看其他类的职责如何。</p>
<h2 id="3、Intercepts与Signature"><a href="#3、Intercepts与Signature" class="headerlink" title="3、Intercepts与Signature"></a>3、Intercepts与Signature</h2><p>在org.apache.ibatis.plugin中存在如下两个注解类：Intercepts与Signature，从字面意思就是用来配置拦截的方法信息。<br><img src="https://img-blog.csdnimg.cn/2019053021040719.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<ul>
<li>Siganature注解的属性说明如下：<ul>
<li>Class&lt;?&gt; type ：需要拦截目标对象的类。</li>
<li>String method：需要拦截目标类的方法名。</li>
<li>Class&lt;?&gt;[] args：需要拦截目标类的方法名的参数类型签名。</li>
</ul>
</li>
</ul>
<p>备注：至于如何得知上述字段的含义，请看下文的Plugin#getSignatureMap方法。</p>
<p>但另外一个类型Plugin类确引起了我的注意。接下来我们将重点分析Plugin方法。</p>
<h2 id="4、Plugin详解"><a href="#4、Plugin详解" class="headerlink" title="4、Plugin详解"></a>4、Plugin详解</h2><h3 id="4-1-Plugin类图"><a href="#4-1-Plugin类图" class="headerlink" title="4.1 Plugin类图"></a>4.1 Plugin类图</h3><p><img src="https://img-blog.csdnimg.cn/20190530210628459.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>其中InvocationHandler为JDK的动态代理机制中的事件执行器，我们可以隐约阈值代理对象的生成将基于JDK内置的动态代理机制。</p>
<p>Plugin的核心属性如下：</p>
<ul>
<li>Object target<br>目标对象。</li>
<li>Interceptor interceptor<br>拦截器对象。</li>
<li>Map&lt;Class&lt;?&gt;, Set&lt; Method&gt;&gt; signatureMap<br>拦截器中的签名映射。</li>
</ul>
<h2 id="4-2-构造函数"><a href="#4-2-构造函数" class="headerlink" title="4.2  构造函数"></a>4.2  构造函数</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">Plugin</span><span class="params">(Object target, Interceptor interceptor, Map&lt;Class&lt;?&gt;, Set&lt;Method&gt;&gt; signatureMap)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.target = target;</span><br><span class="line">    <span class="keyword">this</span>.interceptor = interceptor;</span><br><span class="line">    <span class="keyword">this</span>.signatureMap = signatureMap;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>注意：其构造函数为私有的，那如何构建Plugin呢，其构造方法为Plugin的镜头方法wrap中被调用。</p>
<h3 id="4-3-核心方法详解"><a href="#4-3-核心方法详解" class="headerlink" title="4.3 核心方法详解"></a>4.3 核心方法详解</h3><h4 id="4-3-1-wrap"><a href="#4-3-1-wrap" class="headerlink" title="4.3.1 wrap"></a>4.3.1 wrap</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Object <span class="title">wrap</span><span class="params">(Object target, Interceptor interceptor)</span> </span>&#123;</span><br><span class="line">  Map&lt;Class&lt;?&gt;, Set&lt;Method&gt;&gt; signatureMap = getSignatureMap(interceptor);  <span class="comment">// @1</span></span><br><span class="line">  Class&lt;?&gt; type = target.getClass();   </span><br><span class="line">  Class&lt;?&gt;[] interfaces = getAllInterfaces(type, signatureMap);   <span class="comment">// @2</span></span><br><span class="line">  <span class="keyword">if</span> (interfaces.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> Proxy.newProxyInstance(    <span class="comment">// @3</span></span><br><span class="line">        type.getClassLoader(),</span><br><span class="line">        interfaces,</span><br><span class="line">        <span class="keyword">new</span> Plugin(target, interceptor, signatureMap));</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> target;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：获取待包装的Interceptor的方法签名映射表，稍后详细分析。</p>
<p>代码@2：获取需要代理的对象的Class上声明的所有接口。</p>
<p>代码@3：使用JDK内置的Proxy创建代理对象。Proxy创建代理对象的方法声明如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Object <span class="title">newProxyInstance</span><span class="params">(ClassLoader loader,Class&lt;?&gt;[] interfaces,InvocationHandler h)</span>，</span></span><br></pre></td></tr></table></figure>
<p>注意其事件处理器为Plugin，故在动态运行过程中会执行Plugin的invoker方法。</p>
<p>在进入Plugin#invoker方法学习之前，我们先重点查看一下getSignatureMap、getAllInterfaces的实现。</p>
<h4 id="4-3-2-getSignatureMap"><a href="#4-3-2-getSignatureMap" class="headerlink" title="4.3.2 getSignatureMap"></a>4.3.2 getSignatureMap</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Map&lt;Class&lt;?&gt;, Set&lt;Method&gt;&gt; getSignatureMap(Interceptor interceptor) &#123;</span><br><span class="line">  Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);  <span class="comment">// @1</span></span><br><span class="line">  <span class="keyword">if</span> (interceptsAnnotation == <span class="keyword">null</span>) &#123; <span class="comment">// issue #251                                          // @2</span></span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> PluginException(<span class="string">&quot;No @Intercepts annotation was found in interceptor &quot;</span> + interceptor.getClass().getName());      </span><br><span class="line">  &#125;</span><br><span class="line">  Signature[] sigs = interceptsAnnotation.value();   <span class="comment">// @3</span></span><br><span class="line">  Map&lt;Class&lt;?&gt;, Set&lt;Method&gt;&gt; signatureMap = <span class="keyword">new</span> HashMap&lt;Class&lt;?&gt;, Set&lt;Method&gt;&gt;(); </span><br><span class="line">  <span class="keyword">for</span> (Signature sig : sigs) &#123;</span><br><span class="line">    Set&lt;Method&gt; methods = signatureMap.get(sig.type());</span><br><span class="line">    <span class="keyword">if</span> (methods == <span class="keyword">null</span>) &#123;</span><br><span class="line">      methods = <span class="keyword">new</span> HashSet&lt;Method&gt;();</span><br><span class="line">      signatureMap.put(sig.type(), methods);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      Method method = sig.type().getMethod(sig.method(), sig.args());    </span><br><span class="line">      methods.add(method);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (NoSuchMethodException e) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> PluginException(<span class="string">&quot;Could not find method on &quot;</span> + sig.type() + <span class="string">&quot; named &quot;</span> + sig.method() + <span class="string">&quot;. Cause: &quot;</span> + e, e);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> signatureMap;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先从Interceptor的类上获取Intercepts注解。</p>
<p>代码@2：如果Interceptor的类上没有定义Intercepts注解，则抛出异常，说明我们在自定义插件时，必须要有Intercepts注解。</p>
<p>代码@3：解析Interceptor的values属性（Signature[]）数组，然后存入HashMap&lt;Class&lt;?&gt;, Set&lt; Method&gt;&gt;容器内。</p>
<blockquote>
<p>温馨提示：从这里可以得知：自定义的插件必须定义Intercepts注解，其注解的value值为Signature。</p>
</blockquote>
<h4 id="4-3-3-getAllInterfaces"><a href="#4-3-3-getAllInterfaces" class="headerlink" title="4.3.3 getAllInterfaces"></a>4.3.3 getAllInterfaces</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Class&lt;?&gt;[] getAllInterfaces(Class&lt;?&gt; type, Map&lt;Class&lt;?&gt;, Set&lt;Method&gt;&gt; signatureMap) &#123;</span><br><span class="line">  Set&lt;Class&lt;?&gt;&gt; interfaces = <span class="keyword">new</span> HashSet&lt;Class&lt;?&gt;&gt;();</span><br><span class="line">  <span class="keyword">while</span> (type != <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="keyword">for</span> (Class&lt;?&gt; c : type.getInterfaces()) &#123;</span><br><span class="line">      <span class="keyword">if</span> (signatureMap.containsKey(c)) &#123;</span><br><span class="line">        interfaces.add(c);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    type = type.getSuperclass();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> interfaces.toArray(<span class="keyword">new</span> Class&lt;?&gt;[interfaces.size()]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该方法的实现比较简单，并不是获取目标对象所实现的所有接口，而是返回需要拦截的方法所包括的接口。</p>
<h4 id="4-3-4-invoke"><a href="#4-3-4-invoke" class="headerlink" title="4.3.4 invoke"></a>4.3.4 invoke</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123; <span class="comment">// @1</span></span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    Set&lt;Method&gt; methods = signatureMap.get(method.getDeclaringClass());</span><br><span class="line">    <span class="keyword">if</span> (methods != <span class="keyword">null</span> &amp;&amp; methods.contains(method)) &#123;   <span class="comment">// @2</span></span><br><span class="line">      <span class="keyword">return</span> interceptor.intercept(<span class="keyword">new</span> Invocation(target, method, args));   <span class="comment">// @3</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> method.invoke(target, args);                           <span class="comment">// @4</span></span><br><span class="line">  &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">    <span class="keyword">throw</span> ExceptionUtil.unwrapThrowable(e);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先对其参数列表做一个简单的说明：</p>
<ul>
<li>Object proxy 当前的代理对象</li>
<li>Method method 当前执行的方法</li>
<li>Object[] args 当前执行方法的参数</li>
</ul>
<p>代码@2：获取当前执行方法所属的类，并获取需要被拦截的方法集合。</p>
<p>代码@3：如果需被拦截的方法集合包含当前执行的方法，则执行拦截器的interceptor方法。</p>
<p>代码@4：如果不是，则直接调用目标方法的Invoke方法。</p>
<p>从该方法可以看出Interceptor接口的intercept方法就是拦截器自身需要实现的逻辑，其参数为Invocation，在该方法的结束，需要调用invocation#proceed()方法，进行拦截器链的传播。</p>
<p>从目前的学习中，我们已经了解了Plugin.wrap方法就是生成带来带来类的唯一入口，那该方法在什么地方调用呢？从代码类库中没有找到该方法的调用链，说明该方法是供用户调用的。</p>
<p>再看InterceptorChain方法的pluginAll方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">pluginAll</span><span class="params">(Object target)</span> </span>&#123;   <span class="comment">// @1</span></span><br><span class="line">  <span class="keyword">for</span> (Interceptor interceptor : interceptors) &#123;   <span class="comment">// @2</span></span><br><span class="line">    target = interceptor.plugin(target);           <span class="comment">// @3</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> target;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该方法会遍历用户定义的插件实现类（Interceptor），并调用Interceptor的plugin方法，对target进行拆件化处理，即我们在实现自定义的Interceptor方法时，在plugin中需要根据自己的逻辑，对目标对象进行包装（代理），创建代理对象，那我们就可以在该方法中使用Plugin#wrap来创建代理类。</p>
<p>接下来我们再来用序列图来对上述源码分析做一个总结：<br><img src="https://img-blog.csdnimg.cn/2019053021182314.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>看到这里，大家是否对上面提出的3个问题都已经有了自己的答案了。</p>
<p>问题1：InterceptorChain中的interceptors是从什么时候初始化的呢，即拦截链中的拦截器从何而来。<br>答：在初始化SqlSesstionFactory的时候，会解析属性plugins属性，会加载所有的拦截器到InterceptorChain中。</p>
<p>问题2：从前面也得知，无论是创建Executor，还是创建StatementHandler等，都是调用InterceptorChain#pluginAll方法，那是不是拦截器中的拦截器都会作用与目标对象，这应该是有问题的，该如何处理？</p>
<p>答案是在各自订阅的Interceptor#plugin方法中，我们可以根据传入的目标对象，是否是该拦截器关注的，如果不关注，则直接返回目标对象，如果关注，则使用Plugin#wrap方法创建代理对象。</p>
<p>问题3：代理对象是如何创建的？<br>代理对象是使用JDK的动态代理机制创建，使用Plugin#wrap方法创建。</p>
<h2 id="5、实践"><a href="#5、实践" class="headerlink" title="5、实践"></a>5、实践</h2><p>实践是检验真理的唯一标准，那到底如何使用Mybatis的插件机制呢？<br>创建自定义的拦截器Interceptor,实现Interceptor接口。<br>1）实现plugin方法，在该方法中决定是否需要创建代理对象，如果创建，使用Plugin#wrap方法创建。<br>2）实现interceptor方法，该方法中定义拦截器的逻辑，并且在最后请调用invocation.proceed()方法传递拦截器链。<br>3）使用Intercepts注解，定义需要拦截目标对象的方法签名，支持多个。<br>将实现的Interceptor在定义SqlSessionFactory的配置中，放入plugins属性。</p>
<p>最后给出一个Mybatis Plugin插件机制使用案例：基于Mycat+Mybatis的多租户方案：<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/52662426">基于Mybatis与Mycat的多租户方式，通过Mybatis的插件机制，动态改写SQL语句来实现多租户</a></p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/9b5ea02.html" rel="next" title="踩坑记：rocketmq-console 消费TPS为0，但消息积压数却在降低是个什么“鬼”">
                <i class="fa fa-chevron-left"></i> 踩坑记：rocketmq-console 消费TPS为0，但消息积压数却在降低是个什么“鬼”
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/47c4bb93.html" rel="prev" title="源码分析Mybatis MapperProxy初始化之Mapper对象的扫描与构建">
                源码分析Mybatis MapperProxy初始化之Mapper对象的扫描与构建 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E5%9B%9E%E9%A1%BE"><span class="nav-number">1.</span> <span class="nav-text">1、回顾</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-Configuration-newExecutor"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 Configuration#newExecutor</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81InterceptorChain"><span class="nav-number">2.</span> <span class="nav-text">2、InterceptorChain</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E7%B1%BB%E5%9B%BE"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 类图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E6%A0%B8%E5%BF%83%E6%96%B9%E6%B3%95%E4%B8%80%E8%A7%88"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 核心方法一览</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-pluginAll"><span class="nav-number">2.2.1.</span> <span class="nav-text">2.2.1 pluginAll</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-addInterceptor"><span class="nav-number">2.2.2.</span> <span class="nav-text">2.2.1 addInterceptor</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81Intercepts%E4%B8%8ESignature"><span class="nav-number">3.</span> <span class="nav-text">3、Intercepts与Signature</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81Plugin%E8%AF%A6%E8%A7%A3"><span class="nav-number">4.</span> <span class="nav-text">4、Plugin详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-Plugin%E7%B1%BB%E5%9B%BE"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 Plugin类图</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-number">5.</span> <span class="nav-text">4.2  构造函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-%E6%A0%B8%E5%BF%83%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">5.1.</span> <span class="nav-text">4.3 核心方法详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-wrap"><span class="nav-number">5.1.1.</span> <span class="nav-text">4.3.1 wrap</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-getSignatureMap"><span class="nav-number">5.1.2.</span> <span class="nav-text">4.3.2 getSignatureMap</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-3-getAllInterfaces"><span class="nav-number">5.1.3.</span> <span class="nav-text">4.3.3 getAllInterfaces</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-4-invoke"><span class="nav-number">5.1.4.</span> <span class="nav-text">4.3.4 invoke</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5%E3%80%81%E5%AE%9E%E8%B7%B5"><span class="nav-number">6.</span> <span class="nav-text">5、实践</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
